const http = require('http');
const WebSocket = require('ws');

class Test1000Horse {
  constructor() {
    this.ws = null;
    this.userId = null;
  }

  async run () {
    try {
      await this.login();
      await this.connect();
      await this.queryCharacters();
      await this.selectCharacter();
      await this.test1000();
    } catch (error) {
      console.error('测试失败:', error.message);
    } finally {
      if (this.ws) this.ws.close();
    }
  }

  async login () {
    return new Promise((resolve, reject) => {
      const data = JSON.stringify({ mobile: '17091271111', pwd: '123456' });
      const req = http.request({
        hostname: 'localhost', port: 3000, path: '/user-service/user/login',
        method: 'POST', headers: { 'Content-Type': 'application/json' }
      }, (res) => {
        let body = '';
        res.on('data', chunk => body += chunk);
        res.on('end', () => {
          const response = JSON.parse(body);
          if (response.code === 0) {
            this.userId = response.data.userId;
            console.log('✅ 登录成功');
            resolve();
          } else {
            reject(new Error(response.msg));
          }
        });
      });
      req.write(data);
      req.end();
    });
  }

  async connect () {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket('ws://localhost:3000/user-service/websocket');
      this.ws.on('open', () => { console.log('✅ WebSocket连接成功'); resolve(); });
      this.ws.on('error', reject);
    });
  }

  async queryCharacters () {
    return new Promise((resolve) => {
      const handler = (msg) => {
        const data = JSON.parse(msg.toString());
        if (data.act_id === 3) {
          this.ws.removeListener('message', handler);
          console.log('✅ 查询角色成功');
          resolve();
        }
      };
      this.ws.on('message', handler);
      this.ws.send(JSON.stringify({ c: 3, d: {} }));
      setTimeout(() => { this.ws.removeListener('message', handler); resolve(); }, 3000);
    });
  }

  async selectCharacter () {
    return new Promise((resolve) => {
      const handler = (msg) => {
        const data = JSON.parse(msg.toString());
        if (data.act_id === 4) {
          this.ws.removeListener('message', handler);
          console.log('✅ 选择角色成功');
          resolve();
        }
      };
      this.ws.on('message', handler);
      this.ws.send(JSON.stringify({ c: 4, d: { id: 2001 } }));
      setTimeout(() => { this.ws.removeListener('message', handler); resolve(); }, 3000);
    });
  }

  async test1000 () {
    return new Promise((resolve) => {
      const handler = (msg) => {
        const data = JSON.parse(msg.toString());
        if (data.act_id === 1000) {
          this.ws.removeListener('message', handler);
          console.log('✅ 1000指令执行成功');
          console.log('📊 角色信息:');
          console.log('   等级:', data.data.lvl);
          console.log('   攻击力(ap):', data.data.ap);
          console.log('   生命值(hp):', data.data.hp);
          console.log('   法力值(mp):', data.data.mp);
          console.log('   速度(sp):', data.data.sp);
          console.log('');
          console.log('🎯 属性点信息:');
          console.log('   已分配力量(app):', data.data.app);
          console.log('   已分配体质(hpp):', data.data.hpp);
          console.log('   已分配智力(mpp):', data.data.mpp);
          console.log('   已分配敏捷(spp):', data.data.spp);
          console.log('   剩余可分配点数(p):', data.data.p);
          console.log('');
          console.log('🐎 坐骑信息:');
          if (data.data.horse) {
            console.log('   坐骑ID:', data.data.horse.id);
            console.log('   坐骑名称:', data.data.horse.name);
            console.log('   ✅ 坐骑信息返回正常');
          } else {
            console.log('   ❌ 没有上阵坐骑或坐骑信息获取失败');
          }

          // 验证属性点逻辑
          const level = data.data.lvl;
          const totalPoints = (level - 1) * 4;
          const usedPoints = data.data.app + data.data.hpp + data.data.mpp + data.data.spp;
          const availablePoints = data.data.p;
          const calculatedTotal = usedPoints + availablePoints;

          console.log('');
          console.log('🔍 属性点验证:');
          console.log('   等级:', level);
          console.log('   应有总点数:', totalPoints, '(每级4点)');
          console.log('   已使用点数:', usedPoints);
          console.log('   剩余点数:', availablePoints);
          console.log('   实际总点数:', calculatedTotal);

          const minPoints = level;
          const strengthValid = data.data.app >= minPoints;
          const constitutionValid = data.data.hpp >= minPoints;
          const intelligenceValid = data.data.mpp >= minPoints;
          const agilityValid = data.data.spp >= minPoints;

          console.log('');
          console.log('✅ 属性点最低值验证:');
          console.log('   力量 >= 等级:', strengthValid, '(' + data.data.app + ' >= ' + minPoints + ')');
          console.log('   体质 >= 等级:', constitutionValid, '(' + data.data.hpp + ' >= ' + minPoints + ')');
          console.log('   智力 >= 等级:', intelligenceValid, '(' + data.data.mpp + ' >= ' + minPoints + ')');
          console.log('   敏捷 >= 等级:', agilityValid, '(' + data.data.spp + ' >= ' + minPoints + ')');

          const allValid = strengthValid && constitutionValid && intelligenceValid && agilityValid;
          const pointsValid = calculatedTotal === totalPoints;

          console.log('');
          console.log('🎉 验证结果:');
          console.log('   属性点计算:', pointsValid ? '✅ 正确' : '❌ 错误');
          console.log('   最低值保证:', allValid ? '✅ 正确' : '❌ 错误');
          console.log('   坐骑信息:', data.data.horse ? '✅ 正常' : '⚠️ 无坐骑');
          console.log('   总体状态:', pointsValid && allValid ? '🎉 完全正确' : '⚠️ 需要修复');

          resolve();
        }
      };
      this.ws.on('message', handler);
      this.ws.send(JSON.stringify({ c: 1000, d: {} }));
      setTimeout(() => { this.ws.removeListener('message', handler); resolve(); }, 3000);
    });
  }
}

new Test1000Horse().run();


